package org.shop.controller.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.GoodsClassify;
import org.shop.entity.Merchant;
import org.shop.entity.SystemMessage;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.GoodsClassifyService;
import org.shop.service.GoodsService;
import org.shop.service.MerchantService;
import org.shop.service.SystemMessageService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ManagerMerchantController {
	
	private static Logger logger = LogManager.getLogger(ManagerMerchantController.class);
	
	@Autowired
	private MerchantService merchantService;
	@Autowired
    private UserService userService;
	@Autowired
    private GoodsClassifyService goodsClassifyService;
	@Autowired
	private SystemMessageService systemMessageService;
	@Autowired
	private GoodsService goodsService;
	
	/** 
	* @Title: getCheckOfShopList 
	* @Description: TODO(获取正在审核的店铺列表) 
	* @param @param req
	* @param @return     
	* @return Map<String,Object>    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/getCheckOfShopList")
	@ResponseBody
	public Map<String,Object> getCheckOfShopList(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
	 	String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String merchantName = req.getParameter("merchantName");
		try{
			Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("merchantName", merchantName);
            map = merchantService.getCheckOfShopList(paramMap);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/** 
	* @Title: rejectShop 
	* @Description: TODO(驳回店铺) 
	* @param @param req
	* @param @return     
	* @return int    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/rejectShop")
	@ResponseBody
	public int rejectShop(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		int num = 0;
		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
		String rejectReason = req.getParameter("rejectReason");
		try{
			Merchant selectByPrimaryKey = merchantService.selectByPrimaryKey(merchantId);
			paramMap.put("merchantId", merchantId);
			Users userInfoByConditions = userService.getUserInfoByConditions(paramMap);
			if(selectByPrimaryKey.getMerchantType()==1) {
				Merchant t = new Merchant();
				t.setMerchantId(merchantId);
				t.setRejectReason(rejectReason);
				t.setState((byte) 3);
				num = merchantService.updateByPrimaryKeySelective(t);
			//大学生驳回得merchantid置空
			}else if(selectByPrimaryKey.getMerchantType()==2) {
				merchantService.deleteByPrimaryKey(merchantId);
				userInfoByConditions.setMerchantId(null);
				num = userService.updateByPrimaryKey(userInfoByConditions );
			}
			SystemMessage systemMessage = new SystemMessage();
			systemMessage.setreceiveId(userInfoByConditions.getUserId());
			//店铺驳回
			if(num>0&&selectByPrimaryKey.getMerchantType()==1) {
				systemMessage.setMessageContent(userInfoByConditions.getLoginName()+"的"+selectByPrimaryKey.getMerchantName()+"的小店被驳回了,驳回的原因"+rejectReason+"~");
				systemMessage.setMessageType((byte) 1);
				systemMessage.setSendId(ud.getUserId());
				systemMessageService.insertSelective(systemMessage);
			//大学生驳回
			}else if(num>0&&selectByPrimaryKey.getMerchantType()==2) {
				systemMessage.setMessageContent(userInfoByConditions.getLoginName()+"的"+selectByPrimaryKey.getMerchantName()+"的小店被驳回了,驳回的原因"+rejectReason+"~");
				systemMessage.setMessageType((byte) 1);
				systemMessage.setSendId(ud.getUserId());
				systemMessageService.insertSelective(systemMessage);
				userInfoByConditions.setUserType((long) 3);
				userService.updateByPrimaryKeySelective(userInfoByConditions);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	/** 
	* @Title: passShop 
	* @Description: TODO(店铺申请打开店铺) 
	* @param @param req
	* @param @return     
	* @return int    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/passShop")
	@ResponseBody
	public int passShop(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		int num = 0;
		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
		try{
			Merchant t = merchantService.selectByPrimaryKey(merchantId);
			t.setMerchantId(merchantId);
			paramMap.put("merchantId", merchantId);
			Users userInfoByConditions = userService.getUserInfoByConditions(paramMap);
			SystemMessage systemMessage = new SystemMessage();
			systemMessage.setreceiveId(userInfoByConditions.getUserId());
			//店铺开店审核
			if(t.getMerchantType()==1&&t.getState()==1) {
				systemMessage.setMessageContent("恭喜"+userInfoByConditions.getLoginName()+","+t.getMerchantName()+"小店审核通过了~");
				systemMessage.setMessageType((byte) 1);
				systemMessage.setSendId(ud.getUserId());
				systemMessageService.insertSelective(systemMessage);
			//大学生开店审核
			}else if(t.getMerchantType()==2&&t.getState()==1) {
				systemMessage.setMessageContent("恭喜"+userInfoByConditions.getLoginName()+"大学生,"+t.getMerchantName()+"小店审核通过了~");
				systemMessage.setMessageType((byte) 1);
				systemMessage.setSendId(ud.getUserId());
				systemMessageService.insertSelective(systemMessage);
				userInfoByConditions.setUserType((long) 3);
				userService.updateByPrimaryKeySelective(userInfoByConditions);
			}
			if(t.getState()==0) {
				goodsService.openThisGoods(merchantId);
			}
			t.setState((byte) 2);
			num = merchantService.updateByPrimaryKeySelective(t);
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	/** 
	* @Title: stopShop 
	* @Description: TODO(店铺申请关闭店铺) 
	* @param @param req
	* @param @return     
	* @return int    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/stopShop")
	@ResponseBody
	public int stopShop(HttpServletRequest req){
		int num = 0;
		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
		try{
			Merchant t = new Merchant();
			t.setMerchantId(merchantId);
			t.setState((byte) 0);
			num = merchantService.updateByPrimaryKeySelective(t);
			if(num>0) {
				goodsService.closeThisGoods(merchantId);
			}
		}catch(Exception e){
			num = 0;
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	/** 
	* @Title: toMerchantDetail 
	* @Description: TODO(跳转店铺详细页面) 
	* @param @param req
	* @param @return     
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/toMerchantDetail")
	public String toMerchantDetail(HttpServletRequest req){
		req.setAttribute("merchantId", req.getParameter("merchantId"));
		return "manager/merchantDetail";
	};
	
	/** 
	* @Title: getShopInfoByMerchantId 
	* @Description: TODO(根据id获取店铺信息) 
	* @param @param req
	* @param @return     
	* @return Map<String,Object>    返回类型 
	* @throws 
	*/
	@RequestMapping("manager/getShopInfoByMerchantId")
	@ResponseBody
	public Map<String, Object> getShopInfoByMerchantId(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
		try {
			Merchant merchant=merchantService.selectByPrimaryKey(merchantId);
			paramMap.put("merchantId", merchantId);
			Users userInfoByConditions = userService.getUserInfoByConditions(paramMap);
			map.put("merchant", merchant);
			map.put("userName", userInfoByConditions.getUserName());
			map.put("realName", userInfoByConditions.getRealName());
			map.put("idNo", userInfoByConditions.getIdNo());
			map.put("userType", userInfoByConditions.getUserType());
		} catch(Exception e) {
			logger.error(e);
		}
		return map;
	}
	
	/**
	 * 获取全部商家
	 * @param req
	 * @return
	 */
	@RequestMapping("manager/getAllMerchantList")
	@ResponseBody
	public Map<String, Object> getMerchantList(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String merchantName = req.getParameter("merchantName");
        String userName = req.getParameter("userName");
		//获取登录人用户信息
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("userName", userName);
            paramMap.put("states", new int[]{2,0});
            paramMap.put("merchantName", merchantName);
            map = merchantService.getAllShopList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
		return map;
	}

	/**
	 * 获取所有的商家信息
	 * @return
	 */
	@RequestMapping("manager/getAllMerchantInfo")
	@ResponseBody
	public List<Merchant> getAllMerchantInfo(){
		List<Merchant> allMerchantInfo = merchantService.getAllMerchantInfo();
		return allMerchantInfo;
	}
	
	
	/**
     * 获取商品图片
     * @param req
     * @return
     */
    @RequestMapping("manager/getGoodsPhoto")
    public void getGoodsPhoto(HttpServletRequest req,HttpServletResponse res){
        String photoStr=req.getParameter("photoUrl");
        OutputStream os =null;
        InputStream is =null;
        FTPClient ftpClient =null;
        try {
            res.setContentType("image/jpg");
            ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
            if(photoStr.lastIndexOf("/")>0){
                FtpUtil2.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
                is=FtpUtil2.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
            }else{
                is=FtpUtil2.retrieveFileStream(photoStr, ftpClient);
            }
            os=res.getOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                os.close();
            } catch (IOException e) {
                os=null;
            }
            try {
                is.close();
            } catch (IOException e) {
                is=null;
            }
        }
    }
}
